import React, { Component } from "react";
import { Button, Input, Icon, Alert, Modal, message } from "antd";
import { messages } from "share/common";
import "styles/pay/pay-workbench/scan-pay.scss";
import Space from "components/space";
import Condition from "components/condition";
import WaterMark from "components/water-mark";
import ResizeTable from "components/resize-table/resize-table";
import DataHoc from "../../template/data-hoc";
import PayModal from "./pay-modal";
import paymentService from "containers/pay/pay-workbench/pay-workbench.service";
import menuRoute from "routes/menuRoute";

const { If } = Condition;

class ScanPay extends Component {
  key = "Scan";

  state = {
    identifying: false,
    inputValue: "",
    rowSelection: this.props.getSelection(this.props.noticeAlert)(false),
    tableTitle: [],
    selectedData: [],
    data: [],
    visible: false,
  };

  componentDidMount() {
    setTimeout(() => {
      this.input.focus();
    }, 300);
  }

  handlePressEnter = () => {
    const { bankInfo, paymentCompanyId, setOfBookId, radioValue, currencyCode } = this.props.location.state;
    let { inputValue, data, rowSelection } = this.state;
    let params = {
      setOfBookId: setOfBookId.id,
      companyId: (paymentCompanyId || []).map((item) => item.id),
      currencyCode,
      paymentMethodCategory: radioValue,
      code: inputValue,
      accountNumber: bankInfo.companyBank.bankAccountNumber,
    };
    !params.companyId && bankInfo && (params.companyId = bankInfo.paymentAuthCompanyIds || null);
    !params.currencyCode &&
      bankInfo &&
      bankInfo.companyBank &&
      !bankInfo.companyBank.multiCurrencyPay &&
      (params.currencyCode = bankInfo.companyBank.currencyCode);
    this.setState({ identifying: true });
    paymentService
      .scanData(params)
      .then((res) => {
        let temp = res.data.filter((item) => !data.find((record) => record.id === item.id));
        data = temp.concat(data);
        rowSelection.selectedRowKeys = temp.map((item) => item.id).concat(rowSelection.selectedRowKeys);
        this.setState({ data, identifying: false, inputValue: "", rowSelection }, () => {
          rowSelection.onSelectAll(true, [], temp);
          setTimeout(() => {
            this.input.focus();
          }, 0);
        });
      })
      .catch((e) => {
        message.error(e.response.data.message);
        this.setState({ identifying: false });
      });
  };

  handlePay = () => {
    const { bankInfo } = this.props.location.state;
    const { selectedData } = this.state;
    if (
      bankInfo.accountType === "BANKCARD_ACCOUNT" &&
      selectedData.filter((item) => item.accountType === "ALIPAY_LOGON_ID").length
    ) {
      Modal.error({
        title: messages("finance-4.key113") /*所选行中有收款账户为支付宝账户的数据，请返回检查后再确认支付*/,
      });
      return -1;
    }
    let flag = true;
    selectedData.every((item) => {
      if (item.currency === selectedData[0].currency) {
        return true;
      }
      flag = false;
      return false;
    });
    if (!flag) {
      Modal.error({
        title: messages("finance-4.key416") /*不允许跨币种组批，请重新选择付款数据。*/,
      });
      return -1;
    }
    this.setState({ visible: true });
  };

  handleOk = () => {
    const { selectedData, data } = this.state;
    this.setState(
      {
        visible: false,
        data: data.filter((item) => selectedData.findIndex((record) => record.id === item.id) === -1),
      },
      () => {
        this.props.onClearSelected(() => this.props.noticeAlert([]));
      }
    );
  };

  handleClickSwitch = () => {
    this.context.router.push(menuRoute.getRouteItem("pay-workbench").url);
  };

  render() {
    const { identifying, inputValue, rowSelection, tableTitle, selectedData, data, visible } = this.state;
    const { getColumns, handleTableTitle } = this.props;
    const { bankInfo, paymentCompanyId, setOfBookId, radioValue } = this.props.location.state;
    return (
      <div
        style={{
          margin: "-16px -20px 0",
          padding: "16px 20px 0px",
          position: "absolute",
          height: "calc(100vh - 88px)",
          right: "20px",
          left: "20px",
          overflow: "auto",
          background: "#f0f2f5",
        }}
      >
        <div
          style={{
            position: "absolute",
            background: "#fff",
            width: "calc(100% - 40px)",
          }}
        >
          <WaterMark />
          <div className={"scan-pay"}>
            <div className="scan-pay-header">
              <Button type="primary" icon="layout" className="btn-change" onClick={this.handleClickSwitch}>
                {messages("finance-4.key445") /*普通支付*/}
              </Button>
              <h1>{messages("finance-4.key446") /*扫码枪支付*/}</h1>
            </div>
            <Space direction={"vertical"} size={"middle"}>
              <div>
                {messages("finance-4.key66") /*账套*/}：{setOfBookId.setOfBooksName}
              </div>
              <div>
                {messages("finance-4.key272") /*单据公司*/}：{((paymentCompanyId || [])[0] || {}).name || "-"}
              </div>
              <div>
                {messages("finance-4.key175") /*付款方式类型*/}：
                {
                  radioValue === "ONLINE_PAYMENT"
                    ? messages("finance-4.key180") /*线上支付*/
                    : radioValue === "OFFLINE_PAYMENT"
                    ? messages("finance-4.key181") /*线下支付*/
                    : messages("finance-4.key182") /*落地文件支付*/
                }
              </div>
              <div>
                {messages("finance-4.key192") /*付款账户*/}：
                {`${bankInfo.companyBank.bankAccountName} - ${bankInfo.companyBank.bankAccountNumber}${
                  bankInfo.companyBank.bankBranchName ? ` - ${bankInfo.companyBank.bankBranchName}` : ""
                }`}
                {bankInfo.bankPayInfo &&
                  bankInfo.bankPayInfo.status === "Y" &&
                  bankInfo.accountType !== "ALIPAY_LOGON_ID" && (
                    <span style={{ color: "#108ee9" }}>{messages("finance-4.key193") /*（银企直联生效中）*/}</span>
                  )}
              </div>
            </Space>
            <div style={{ position: "relative", margin: "32px 0" }}>
              <Input
                value={inputValue}
                onChange={(e) => this.setState({ inputValue: e.target.value })}
                onPressEnter={this.handlePressEnter}
                style={{ fontSize: "16px", fontWeight: "bold" }}
                ref={(input) => (this.input = input)}
                className="input-search"
                disabled={identifying}
              />
              <p
                style={{
                  color: "#8B93A7",
                  marginTop: "8px",
                }}
              >
                {
                  messages(
                    "expense-14.key267"
                  ) /*若您扫码后提示单据不存在，或无法跳转至单据详情页，请尝试：1. 输入法切换至英文环境后再扫码；2. 确认您的扫码枪已设置回车后缀*/
                }
              </p>
              <Condition>
                <If value={identifying}>
                  <Icon
                    type="loading"
                    style={{
                      position: "absolute",
                      top: "8px",
                      right: "8px",
                      zIndex: 1,
                    }}
                  />
                </If>
              </Condition>
            </div>
          </div>
        </div>
        <div
          style={{
            width: "calc(100%)",
            position: "absolute",
            margin: "0px -20px",
            background: "#fff",
            bottom: "0",
            height: "calc(100vh - 513px)",
            overflowY: "auto",
          }}
          className={"scan-table"}
        >
          <WaterMark />
          <div style={{ padding: "0 20px", margin: "12px 0" }}>
            <Alert
              message={
                messages(
                  "finance-4.key447"
                ) /*请注意，扫码枪成功扫描识别后有未支付金额的单据会显示在此处，当前付款账户可支付的单据会自动勾选上*/
              }
              type="info"
              showIcon
              style={{ width: "100%" }}
            />
          </div>
          <ResizeTable
            tableName="pay-Unpaid"
            columns={getColumns(this.key)}
            rowSelection={rowSelection}
            dataSource={data}
            showUtils
            rowKey={"id"}
            pagination={{ pageSize: 1000 }}
            title={() => handleTableTitle(tableTitle, selectedData)}
          />
          <div className="scan-table-footer">
            <span>
              {messages("common-1.key27") /*已选择*/}
              <span className="scan-table-footer-selected-number">{rowSelection.selectedRowKeys.length}</span>
            </span>
            <div
              className={this.classNames({
                "scan-table-footer-area": !!rowSelection,
              })}
            >
              <Button type={"primary"} onClick={this.handlePay} disabled={selectedData.length === 0}>
                {
                  radioValue === "ONLINE_PAYMENT"
                    ? messages("finance-4.key180") /*线上支付*/
                    : radioValue === "OFFLINE_PAYMENT"
                    ? messages("finance-4.key181") /*线下支付*/
                    : messages("finance-4.key182") /*落地文件支付*/
                }
              </Button>
            </div>
          </div>
        </div>
        <PayModal
          radioValue={radioValue}
          visible={visible}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          record={selectedData}
          setOfBookId={setOfBookId.id}
          onOk={this.handleOk}
          bankInfo={bankInfo}
        />
      </div>
    );
  }
}

ScanPay.contextTypes = {
  router: React.PropTypes.object,
};

export default DataHoc(ScanPay);
